import { ApiResponse, Article, Channel } from '@/types/data'
import { ChannelAction, RootThunkAction } from '@/types/store'
import request from '@/utils/request'
import { getChannels, getToken, hasToken, setChannels } from '@/utils/storage'

export const getUserChannel = (): RootThunkAction => {
  return async (dispatch) => {
    /* 
     1.判断用户是否登录
     2.若登录了，直接发送请求获取数据
     3.若没登录
       优先获取本地数据，判断是否有本地数据
       若有本地数据，直接使用
       若没有本地数据，发送请求获取默认的频道数据，且存储在本地
    */
    const token = getToken().token
    if (token) {
      const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
        '/user/channels'
      )
      dispatch({
        type: 'home/getUserChannel',
        payload: res.data.data.channels,
      })
      setChannels(res.data.data.channels)
    } else {
      const userChannels = getChannels()
      if (userChannels.length > 0) {
        dispatch({
          type: 'home/getUserChannel',
          payload: userChannels,
        })
      } else {
        const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
          '/user/channels'
        )
        dispatch({
          type: 'home/getUserChannel',
          payload: res.data.data.channels,
        })
        setChannels(res.data.data.channels)
      }
    }
  }
}

export const getAllChannel = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
      '/channels'
    )
    dispatch({
      type: 'home/getAllChannel',
      payload: res.data.data.channels,
    })
  }
}

export const changeActive = (id: number): ChannelAction => {
  return {
    type: 'home/changeActive',
    payload: id,
  }
}

export const addChannel = (channel: Channel): RootThunkAction => {
  /* 
  判断用户是否登录
  1.如果登录，发送请求添加到频道
  2.如果没有登录，吧频道添加到loccalstorage中
  */
  return async (dispatch, getState) => {
    const channels = getState().channel.userChannels
    if (hasToken()) {
      await request.patch('/user/channels', {
        channels: [channel],
      })
    } else {
      setChannels([...channels, channel])
    }
    // dispatch(getUserChannel())
    dispatch({
      type: 'home/updateUserChannel',
      payload: [...channels, channel],
    })
  }
}

export const deleteChannel = (channel: Channel): RootThunkAction => {
  /* 
  判断用户是否登录
  1.如果登录，发送请求添加到频道
  2.如果没有登录，吧频道添加到loccalstorage中
  */
  return async (dispatch, getState) => {
    let channels = getState().channel.userChannels
    channels = channels.filter((item) => item.id !== channel.id)
    if (hasToken()) {
      await request.delete(`/user/channels/${channel.id}`)
    } else {
      setChannels([...channels])
    }
    dispatch({
      type: 'home/updateUserChannel',
      payload: [...channels],
    })
  }
}

export const getArticleList = (
  channel_id: number,
  timestamp: number
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<
      ApiResponse<{ pre_timestamp: string; results: Article[] }>
    >('/articles', {
      params: {
        channel_id,
        timestamp,
      },
    })
    dispatch({
      type: 'home/getArticles',
      payload: {
        ...res.data.data,
        channel_id,
      },
    })
  }
}

export const getNewArticleList = (
  channel_id: number,
  timestamp: number
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<
      ApiResponse<{ pre_timestamp: string; results: Article[] }>
    >('/articles', {
      params: {
        channel_id,
        timestamp,
      },
    })
    dispatch({
      type: 'home/getNewArticles',
      payload: {
        ...res.data.data,
        channel_id,
      },
    })
  }
}
